/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers.changePassword;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputSecret;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Ida
 */
@FacesValidator("javaclass.SamePasswordValidator")
public class SamePasswordValidator implements Validator {

    public SamePasswordValidator() {
    }

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        HtmlInputSecret secondInput = (HtmlInputSecret) component;

        final String secondVal = value.toString(),
                     firstVal = getMatchingHtmlInputSecret(secondInput);

        final boolean matchesConfirmation = secondVal.equals(firstVal);

        if (!matchesConfirmation) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    secondInput.getLabel() + " Validation Error: Passordene må være like",
                    secondInput.getLabel() + " Validation Error: Begge passordene må være like" ));
        }
    }

    private String getMatchingHtmlInputSecret(final HtmlInputSecret second) {
        int i = 0;
        for (UIComponent uic : second.getParent().getChildren())
            if (uic != second && uic instanceof HtmlInputSecret
            && i++ == 1) {
                final HtmlInputSecret found = (HtmlInputSecret) uic;
                System.err.print(found.getLabel());
                return (String) found.getLocalValue();
            }
        throw new RuntimeException("Should never reach here");
    }
}

